package com.example.configcenter.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

/**
 * Description: .
 *
 * @author Wengy
 * @since JDK 1.8
 * @since 1.0.0
 */
@Configuration
public class DruidDataSourceConfig {
    
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Bean
    DataSource getDataSource() throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181")
                .retryPolicy(retryPolicy).sessionTimeoutMs(1000 * 6).connectionTimeoutMs(1000 * 6).namespace("config").build();
        client.start();
        
        String jsonStr = new String(client.getData().forPath("/datasource"));
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(jsonObject.getString("url"));
        druidDataSource.setUsername(jsonObject.getString("userName"));
        druidDataSource.setPassword(jsonObject.getString("password"));
        druidDataSource.setDriverClassName(jsonObject.getString("driverClassName"));
    
        String path = "/datasource";
        TreeCache treeCache = new TreeCache(client, path);
    
        treeCache.getListenable().addListener(new TreeCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
                ChildData eventData = event.getData();
                switch (event.getType()) {
                    case NODE_ADDED:
                        logger.warn(path + "节点添加" + eventData.getPath() + "\t添加数据为：" + new String(eventData.getData()));
                        break;
                    case NODE_UPDATED:
                        logger.warn(eventData.getPath() + "节点数据更新\t更新数据为：" + new String(eventData.getData()) + "\t版本为：" + eventData.getStat().getVersion());
                        break;
                    case NODE_REMOVED:
                        logger.warn(eventData.getPath() + "节点被删除");
                        break;
                    default:
                        break;
                }
            }
        });
        treeCache.start();
        
        return  druidDataSource;
        
    }
}
